package zh.dummy.netty.core.codec;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import zh.dummy.netty.core.protocol.Header;
import zh.dummy.netty.core.protocol.NettyMessage;

public class NettyMessageDecoder extends ByteToMessageDecoder{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private FastjsonDecoder fastjsonDecoder;
	
	public NettyMessageDecoder(){
		this.fastjsonDecoder = new FastjsonDecoder();
	}
	
	@Override
	protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		Object decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
	}
	protected NettyMessage decode(ChannelHandlerContext ctx,ByteBuf in) {
		int readables = in.readableBytes();
		if(readables <= 0){
			return null;
		}
		NettyMessage msg = new NettyMessage();
		Header header = new Header();
		header.setCrcCode(in.readInt());
		header.setSessionID(in.readLong());
		header.setType(in.readByte());
		header.setPriority(in.readByte());
		header.setAttchment(fastjsonDecoder.decodeHeaderAttch(in));
		msg.setHeader(header);
		if(in.readableBytes() > 0){
			JSONObject body = fastjsonDecoder.decode(in);
			msg.setBody(body);
		}
		if(logger.isDebugEnabled()){
			logger.debug("reveived NettyMessage :　{}",msg.toString());
		}
		return msg;
	}
	
}